package com.lori.netshop.service.imp;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lori.netshop.pojo.Order;
import com.lori.netshop.pojo.TbUser;
import com.lori.netshop.service.OrderService;
import com.lori.netshop.util.CookieUtils;
import com.lori.netshop.util.HttpClientUtil;
import com.lori.netshop.util.NetshopResult;
import com.lori.netshop.util.StringUtil;

@Service
public class OrderServiceimp implements OrderService{
	@Value("${BASE_ORDER}")
	private String BASE_ORDER;
	@Value("${ORDER_CREATE}")
	private String ORDER_CREATE;
	@Value("${BASE_SSO}")
	private String BASE_SSO;
	@Value("${SSO_DATA}")
	private String SSO_DATA;
	@Value("${ORDER_ORDERS}")
	private String ORDER_ORDERS;
	
	
	/**
	 * 创建订单
	 */
	@Override
	public NetshopResult createOrder(Order order, HttpServletRequest request) {
		//获得拦截器存入request的用户对象
		TbUser user = (TbUser) request.getAttribute("user");
		//检查是否登录
		if(user == null){
			return NetshopResult.build(500, "未登录");
		}else{
			ObjectMapper mapper = new ObjectMapper();
			try {
				//补全用户信息
				if(order != null){
					order.setUserId(user.getId());
					order.setBuyerNick(user.getUsername());
					//将order转为json字符串
					String orderjson = mapper.writeValueAsString(order);
					//创建订单
					String string = HttpClientUtil.doPostJson(BASE_ORDER+ORDER_CREATE, orderjson);
					NetshopResult formatToPojo = NetshopResult.format(string);
					Object data = formatToPojo.getData();
					System.out.println(data);
					return NetshopResult.ok(data);
				}
			} catch (IOException e) {
				e.printStackTrace();
				return NetshopResult.build(400, "创建订单失败");
			}
		}
		return NetshopResult.build(400, "创建订单失败");
	}


	@Override
	public List<Order>  getOrders(long userId) {
		// 调用订单系统获得订单数据
		String json = HttpClientUtil.doGet(BASE_ORDER + ORDER_ORDERS+userId);
		System.out.println(json+"---------------------");
		if(!StringUtil.isEmpty(json)){
			//转为java数据
			NetshopResult result = NetshopResult.formatToList(json, Order.class);
			if(result != null){
				List<Order> orders = (List<Order>) result.getData();
				return orders;
			}
			return null;
		}
		return null;
	}

}
